<?php

namespace app\manage\controller;

use support\Request;
use app\manage\controller\Base;
use Gregwar\Captcha\CaptchaBuilder;
use think\facade\Db;

class Index extends Base
{
    public function index(Request $request)
    {
        return view('index/index', [

        ]);
    }

    public function api(Request $request)
    {
        $data = $request->all();
        //初始化数据
        if ($data['type'] == 'init') {
            $nav=Db::name('pilot_nav')->where('isopen',1)->order('sort desc')->column('title','id');
            $arr=[];
            $admin=Db::name('admin')->find(session('uid' ));
            if($admin['id']==1){
                $so=true;
            }else{
                $auth=Db::name('auth')->find($admin['auth']);
                $so=[
                    ['id','in',explode(",", $auth['auth'])]
                ];
            }
            foreach ($nav as $k=>$v){
                $arr1=["title" => $v, "href"=> ""];
                $nav2=Db::name('pilot_list')->where('isopen',1)->where('fid',0)->where('pn_id',$k)->order('sort asc')->select();
                $arr2=[];
                foreach ($nav2 as $v1){
                    $nav3=Db::name('pilot_list')->where('isopen',1)->where($so)->where('fid',$v1['id'])->where('pn_id',$k)->order('sort asc')->select();
                    if(count($nav3)){
                        $arr3=[
                            "title" => $v1['title'],
                            "icon" => "fa ".$v1['icon'],
                            "target"=>"_self",
                            "href"=> $v1['url'] ? '/manage/'.$v1['url'] : '',
                        ];
                        $arr4=[];
                        foreach ($nav3 as $v2){
                            $arr4[]=   [
                                "title" => $v2['title'],
                                "href" => '/manage/'.$v2['url'],
                                "target" => "_self",
                            ];
                        }
                        $arr3['child']=$arr4;
                        $arr2[]=$arr3;
                    }
                }
                $arr1['child']=$arr2;
                $arr[]=$arr1;
            }
            $info = [
                "homeInfo" => [
                    "title" => "首页",
                    "href" => "/manage/index/home"
                ],
                "logoInfo" => [
                    "title" => "unicms v1.0",
                    "image" => "/static/manage/logo.png",
                    "href" => "/manage/index"
                ],
                "menuInfo" => $arr
            ];

            return json($info);
        }
        return json(['code' => 0, 'message' => '非法获取']);
    }

    public function home(Request $request)
    {
        $log=Db::name('log')->order('id desc')->limit(9)->select();
        $l_zong=Db::name('log')->count();
        $c_zong=Db::name('cate')->count();
        $a_zong=Db::name('article')->count();
        $admin_zong=Db::name('admin')->count();
        $info = array(
            '操作系统'=>PHP_OS,
            'PHP运行方式'=>php_sapi_name(),
            '上传附件限制'=>ini_get('upload_max_filesize'),
            '运行框架'=>'webman',
            '执行时间限制'=>ini_get('max_execution_time').'秒',
            '服务器时间'=>date("Y年n月j日 H:i:s"),
            '北京时间'=>gmdate("Y年n月j日 H:i:s",time()+8*3600),
            '剩余空间'=>round((disk_free_space(".")/(1024*1024)),2).'M',
            'register_globals'=>get_cfg_var("register_globals")=="1" ? "ON" : "OFF",
        );

        return view('index/home', [
            'log'=>$log,
            'l_zong'=>$l_zong,
            'c_zong'=>$c_zong,
            'a_zong'=>$a_zong,
            'admin_zong'=>$admin_zong,
            'info'=>$info
        ]);
    }

    public function login(Request $request)
    {
        if ($request->method() == 'POST') {
            $data = $request->post();
            $password = base64_encode($data['password'] . 'lizhili');
            $ip = $request->getRealIp(true);
            $log1 = [
                'username' => $data['username'],
                'ip' => $ip,
                'create_time' => time(),
                'password' => $password
            ];
            $id = Db::name('log')->insertGetId($log1);

            $validate = new \app\manage\validate\Login;
            if (!$validate->check($data)) {
                return tips(0, $validate->getError());
            }
            //验证验证是否正确
            if (strtolower($data['captcha']) !== $request->session()->get('captcha')) {
                return tips(0, '输入的验证码不正确');
            }
            //验证自定义token
            $captcha = $request->post('__token__');
            if ($data['__token__'] !== $request->session()->get('__token__')) {
                return tips(0, '令牌不正确，请刷新后提交！');
            }
            $password = md5(substr(md5($data['password']), 0, 25) . 'lizhili');
            if ($info = Db::name('admin')->where('isopen', 1)->where('username', $data['username'])->where('password', $password)->find()) {
                Db::name('log')->where('id', $id)->update([
                    'admin_id' => $info['id'],
                    'is_cheng' => 1
                ]);
                session(['name' => $info['username'], 'uid' => $info['id']]);
                return tips(1, '数据正确！', 'index/index');
            } else {
                return tips(0, '账号或密码不正确！');
            }
        }
        return view('index/login', ['data' => Db::name('')]);
    }

    public function captcha(Request $request)
    {
        // 初始化验证码类
        $builder = new CaptchaBuilder;
        // 生成验证码
        $builder->build();
        // 将验证码的值存储到session中
        $request->session()->set('captcha', strtolower($builder->getPhrase()));
        // 获得验证码图片二进制数据
        $img_content = $builder->get();
        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

    public function logout(Request $request)
    {
        $request->session()->flush();
        return view('index/login', ['name' => 'webman']);
    }
}
